package project;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ExceptionViewer {
	//private static JLabel userMsgLabel;
	private static JTextArea userMsgLabel;
	private static JTextArea traceBox;
	private static JScrollPane pane;
	private static JButton displaybtn;
	private static JPanel tracePanel;
	private static String showText = "SHOW >>";
	private static String hideText = "HIDE <<";
	private static JDialog jdialog;
	private static JPanel btnPanel;
	
	public static void show(String dialogTitle, String userMsg, Exception exc){
		//userMsgLabel = new JLabel(userMsg);
		userMsgLabel = new JTextArea((userMsg!=null) ? userMsg : exc.getMessage());
		traceBox = new JTextArea(20,60);
		pane = new JScrollPane(traceBox);
		displaybtn = new JButton(showText);
		btnPanel = new JPanel();
		tracePanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
		
		
		JComponent[] components = {userMsgLabel, tracePanel};
		JOptionPane jOption = new JOptionPane(components, JOptionPane.PLAIN_MESSAGE);
		jdialog = jOption.createDialog(dialogTitle);
		
		StringBuilder sb = new StringBuilder();
		for(StackTraceElement elem : exc.getStackTrace()) 
			sb.append(elem.toString()+"\n");
		
		traceBox.setText(sb.toString());

		traceBox.setEditable(false);
		traceBox.setMargin(new Insets(5, 5, 5, 5));
		userMsgLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		traceBox.setFont(new Font("Courier New", Font.PLAIN, 12));
		
		btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
		//btnPanel.setBackground(Color.GRAY);
		btnPanel.add(displaybtn);
		tracePanel.add(btnPanel);
		tracePanel.add(pane);
		pane.setVisible(false);
		tracePanel.setBorder(BorderFactory.createTitledBorder("Exception Stack Trace"));
		
		userMsgLabel.setEditable(false);
		userMsgLabel.setEnabled(false);
		userMsgLabel.setBackground(pane.getBackground());
		userMsgLabel.setLineWrap(true);
		userMsgLabel.setWrapStyleWord(true);
		userMsgLabel.setDisabledTextColor(Color.black);
		userMsgLabel.setPreferredSize(new Dimension(350, 60));

		
		jdialog.pack();
		
		displaybtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				if(!pane.isShowing()){
					displaybtn.setText(hideText);
					pane.setVisible(true);
					btnPanel.setPreferredSize(new Dimension(displaybtn.getPreferredSize().width, pane.getPreferredSize().height));
					jdialog.pack();
				}
				else{
					displaybtn.setText(showText);
					pane.setVisible(false);
					btnPanel.setPreferredSize(new Dimension(displaybtn.getPreferredSize().width, displaybtn.getPreferredSize().height));
					jdialog.pack();
				}
			}
		});
		
		jdialog.setLocation(400, 100);
		jdialog.setVisible(true);
		//jdialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		System.out.print("Done");
		//System.exit(0);
	}
}
